<template>
  <div>
    <div class="header">
      <h1>Todo List</h1>
      <el-button @click="handleLogout">退出登录</el-button>
    </div>
    <div class="search-bar">
      <el-input 
        v-model="searchQuery" 
        placeholder="请输入搜索内容" 
        clearable 
        @clear="clearSearch"
        class="search-input"
      ></el-input>
      <el-button type="primary" class="fixed-width" @click="handleSearch">查询</el-button>
      <el-button class="fixed-width" @click="showCreateDialog">添加</el-button>
    </div>
    <!-- 添加待办事项的对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加待办事项"
      width="30%"
    >
      <el-form :model="newTodo" label-width="80px">
        <el-form-item label="标题">
          <el-input v-model="newTodo.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="newTodo.description"
            type="textarea"
            placeholder="请输入描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCreateTodo">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-table :data="filteredTodos" style="width: 100%">
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>
      <el-table-column label="已完成">
        <template #default="scope">
          <el-switch
            v-model="scope.row.completed"
            @change="(val) => handleToggleComplete(scope.row.id, val)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="handleDelete(scope.row.id)" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加分页组件 -->
    <div class="pagination-container" style="margin-top: 20px; text-align: right;">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next"
      />
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'TodoListHome',
  data() {
    return {
      dialogVisible: false,
      newTodo: {
        title: '',
        description: ''
      },
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
    }
  },
  computed: {
    ...mapState({
      todos: state => state.todos,
      total: state => state.total
    }),
    filteredTodos() {
      return this.todos;
    },
  },
  methods: {
    ...mapActions(['fetchTodos', 'createTodo', 'deleteTodo', 'searchTodos', 'logout', 'updateTodoStatus']),
    showCreateDialog() {
      this.dialogVisible = true
      // 重置表单
      this.newTodo = {
        title: '',
        description: ''
      }
    },
    async handleCreateTodo() {
      if (!this.newTodo.title) {
        ElMessage.warning('请输入标题')
        return
      }
      
      try {
        const result = await this.createTodo(this.newTodo)
        console.log('Create todo result:', result)
        ElMessage.success('添加成功')
        this.dialogVisible = false
      } catch (error) {
        console.error('Create todo error:', error)
        ElMessage.error(error.message)
      }
    },
    clearSearch() {
      this.searchQuery = ''
    },
    async handleSearch() {
      if (this.searchQuery) {
        try {
          await this.searchTodos({ query: this.searchQuery })
          ElMessage.success('搜索成功')
        } catch (error) {
          ElMessage.error('搜索失败，请稍后重试')
        }
      } else {
        ElMessage.warning('请输入搜索内容')
      }
    },
    // 处理页码改变
    async handleCurrentChange(page) {
      this.currentPage = page
      await this.loadTodos()
    },
    // 处理每页条数改变
    async handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      await this.loadTodos()
    },
    // 加载数据的方法
    async loadTodos() {
      try {
        await this.fetchTodos({
          page: this.currentPage,
          pageSize: this.pageSize
        })
      } catch (error) {
        ElMessage.error('加载失败，请稍后重试')
      }
    },
    // 修改表格中的删除按钮点击处理方法
    async handleDelete(id) {
      try {
        await ElMessageBox.confirm(
          '确定要删除这条记录吗？',
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        await this.deleteTodo(id)
        ElMessage.success('删除成功')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败，请稍后重试')
        }
      }
    },
    async handleLogout() {
      try {
        this.logout()
        this.$router.push('/login')
        ElMessage.success('已退出登录')
      } catch (error) {
        ElMessage.error('退出失败')
      }
    },
    async handleToggleComplete(id, completed) {
      try {
        await this.updateTodoStatus({ id, completed })
        ElMessage.success(completed ? '已标记为完成' : '已标记为未完成')
      } catch (error) {
        ElMessage.error('更新状态失败')
        // 恢复原状态
        await this.loadTodos()
      }
    }
  },
  mounted() {
    this.loadTodos()
  },
}
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  display: flex;
  gap: 15px;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
}

/* 修复按钮点击区域问题 */
:deep(.fixed-width) {
  width: 80px;
  padding: 0;
}

:deep(.fixed-width span) {
  width: 100%;
  display: inline-block;
}

/* 确保按钮内容居中 */
:deep(.el-button) {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
